<script setup>
import { ref, onMounted, computed, watch } from 'vue'

// 购物车商品列表
const cartItems = ref([])

// 动画相关状态
const animatedTotalPrice = ref(0)
const animatedTotalCount = ref(0)
const isPageLoaded = ref(false)

// 获取类别对应的图标
const getCategoryIcon = (category) => {
  const categoryIcons = {
    '女装': '👗',
    '男装': '👔',
    '鞋靴': '👟',
    '箱包': '👜',
    '数码': '📱',
    '家电': '📺',
    '家居': '🏠',
    '美妆': '💄',
    '母婴': '👶',
    '食品': '🍔'
  }
  return categoryIcons[category] || '🛍️'
}

// 获取默认商品图片
const getDefaultImage = (category) => {
  const categoryImages = {
    '女装': 'https://img.alicdn.com/imgextra/i1/O1CN012C0rPz1w0GjY6l8tZ_!!6000000006036-2-tps-1000-1000.jpg',
    '男装': 'https://img.alicdn.com/imgextra/i1/O1CN01uIqKpG1jV0ZvNvM5B_!!6000000005086-2-tps-1000-1000.jpg',
    '鞋靴': 'https://img.alicdn.com/imgextra/i2/O1CN01K5Zq7X1b8r1Xv5V5B_!!6000000003945-2-tps-1000-1000.jpg',
    '箱包': 'https://img.alicdn.com/imgextra/i2/O1CN01H5Zq7X1a8r1Xv5V5B_!!6000000003944-2-tps-1000-1000.jpg',
    '数码': 'https://img.alicdn.com/imgextra/i1/O1CN01X0FzNQ27YtU4K2bVQ_!!6000000007990-0-picassoopen.jpg',
    '家电': 'https://img.alicdn.com/imgextra/i4/O1CN01x9KZ0h1zJ1Z8X2ZQ_!!6000000006228-0-picassoopen.jpg',
    '家居': 'https://img.alicdn.com/imgextra/i3/O1CN013vR93t1eZ2wY7Y6qL_!!6000000006001-0-picassoopen.jpg',
    '美妆': 'https://img.alicdn.com/imgextra/i3/O1CN013vR93t1eZ2wY7Y6qL_!!6000000006001-0-picassoopen.jpg',
    '母婴': 'https://img.alicdn.com/imgextra/i3/O1CN013vR93t1eZ2wY7Y6qL_!!6000000006001-0-picassoopen.jpg',
    '食品': 'https://img.alicdn.com/imgextra/i3/O1CN013vR93t1eZ2wY7Y6qL_!!6000000006001-0-picassoopen.jpg'
  }
  return categoryImages[category] || 'https://via.placeholder.com/300?text=商品图片'
}

// 创建模拟商品数据
const createMockItems = () => {
  return [
    {
      id: 101,
      name: '时尚连衣裙',
      category: '女装',
      price: 199,
      image: getDefaultImage('女装')
    },
    {
      id: 102,
      name: '男士休闲鞋',
      category: '鞋靴',
      price: 299,
      image: getDefaultImage('鞋靴')
    },
    {
      id: 103,
      name: '女士手提包',
      category: '箱包',
      price: 399,
      image: getDefaultImage('箱包')
    },
    {
      id: 104,
      name: '男士衬衫',
      category: '男装',
      price: 159,
      image: getDefaultImage('男装')
    }
  ]
}

// 加载购物车数据
const loadCartData = () => {
  const cart = localStorage.getItem('cart')
  if (cart) {
    cartItems.value = JSON.parse(cart)
  } else {
    // 如果购物车为空，添加一些模拟数据以便展示
    cartItems.value = createMockItems()
    localStorage.setItem('cart', JSON.stringify(cartItems.value))
  }
  
  // 确保所有商品都有合适的图片
  cartItems.value = cartItems.value.map(item => ({
    ...item,
    image: item.image || getDefaultImage(item.category || '')
  }))
  
  // 页面加载完成后启动动画
  setTimeout(() => {
    isPageLoaded.value = true
  }, 100)
}

// 计算总价
const totalPrice = computed(() => {
  return cartItems.value.reduce((total, item) => {
    return total + item.price
  }, 0)
})

// 计算商品总数
const totalCount = computed(() => {
  return cartItems.value.length
})

// 从购物车移除商品
const removeFromCart = (index) => {
  // 添加移除动画类
  const item = document.querySelector(`[data-index="${index}"]`)
  if (item) {
    item.classList.add('removing')
    setTimeout(() => {
      cartItems.value.splice(index, 1)
      // 更新本地存储
      localStorage.setItem('cart', JSON.stringify(cartItems.value))
    }, 300)
  } else {
    cartItems.value.splice(index, 1)
    localStorage.setItem('cart', JSON.stringify(cartItems.value))
  }
}

// 结算功能
const checkout = () => {
  if (cartItems.value.length === 0) {
    alert('购物车为空，请先添加商品')
    return
  }
  
  // 添加结算按钮动画
  const checkoutBtn = document.querySelector('.checkout-btn')
  checkoutBtn.classList.add('checking-out')
  
  // 结算动画完成后执行逻辑
  setTimeout(() => {
    // 这里可以实现实际的结算逻辑
    alert(`结算成功！共${totalCount.value}件商品，总价：¥${totalPrice.value}`)
    
    // 清空购物车
    cartItems.value = []
    localStorage.removeItem('cart')
    checkoutBtn.classList.remove('checking-out')
  }, 500)
}

// 数字变化动画函数
const animateNumber = (from, to, duration, updateFn) => {
  const startTime = Date.now()
  const diff = to - from
  
  const animate = () => {
    const currentTime = Date.now()
    const progress = Math.min((currentTime - startTime) / duration, 1)
    // 使用缓动函数使动画更自然
    const easeOutQuad = t => t * (2 - t)
    const currentValue = from + diff * easeOutQuad(progress)
    
    updateFn(currentValue)
    
    if (progress < 1) {
      requestAnimationFrame(animate)
    }
  }
  
  animate()
}

// 监听总价和总数变化，执行动画
watch(totalPrice, (newVal) => {
  animateNumber(animatedTotalPrice.value, newVal, 500, (val) => {
    animatedTotalPrice.value = Math.round(val * 100) / 100
  })
})

watch(totalCount, (newVal) => {
  animateNumber(animatedTotalCount.value, newVal, 500, (val) => {
    animatedTotalCount.value = Math.round(val)
  })
})

onMounted(() => {
  loadCartData()
  // 初始化动画值
  animatedTotalPrice.value = totalPrice.value
  animatedTotalCount.value = totalCount.value
})</script>

<template>
  <div class="cart-page" :class="{ 'page-loaded': isPageLoaded }">
    <div class="container">
      <h2 class="page-title">我的购物车</h2>
      
      <div v-if="cartItems.length === 0" class="empty-cart">
        <p>购物车空空如也，快去添加商品吧！</p>
        <router-link to="/home" class="go-shopping-btn">去购物</router-link>
      </div>
      
      <div v-else class="cart-content">
        <!-- 购物车商品列表 -->
        <div class="cart-items">
          <transition-group name="cart-item" tag="div">
            <div 
              v-for="(item, index) in cartItems" 
              :key="`${item.id}-${index}`" 
              class="cart-item"
              :data-index="index"
            >
              <div class="item-image">
                <img :src="item.image || getDefaultImage(item.category || '')" :alt="item.name" class="item-img" />
                <span v-if="item.category" class="item-category-tag">
                  <span class="category-icon">{{ getCategoryIcon(item.category) }}</span>
                  {{ item.category }}
                </span>
              </div>
              <div class="item-info">
                <div class="item-name">{{ item.name }}</div>
                <div class="item-price">¥{{ item.price }}</div>
              </div>
              <div class="item-actions">
                <button class="remove-btn" @click="removeFromCart(index)">删除</button>
              </div>
            </div>
          </transition-group>
        </div>
        
        <!-- 结算区域 -->
        <div class="checkout-section">
          <div class="checkout-info">
            <div class="total-items">共 <span class="animated-number">{{ animatedTotalCount }}</span> 件商品</div>
            <div class="total-price">合计：<span class="price">¥{{ animatedTotalPrice }}</span></div>
          </div>
          <button class="checkout-btn" @click="checkout">立即结算</button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 页面基础样式 */
.cart-page {
  background-color: #f5f5f5;
  min-height: 60vh;
  padding: 20px 0;
  width: 100%;
  opacity: 0;
  transform: translateY(20px);
  transition: opacity 0.6s ease-out, transform 0.6s ease-out;
}

.cart-page.page-loaded {
  opacity: 1;
  transform: translateY(0);
}

.page-title {
  font-size: 24px;
  color: #333;
  margin-bottom: 20px;
  opacity: 0;
  transform: translateY(-10px);
  transition: opacity 0.4s ease-out, transform 0.4s ease-out;
  transition-delay: 0.2s;
}

.cart-page.page-loaded .page-title {
  opacity: 1;
  transform: translateY(0);
}

/* 空购物车样式 */
.empty-cart {
  text-align: center;
  padding: 60px 0;
  background-color: #fff;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  width: 100%;
  opacity: 0;
  transform: scale(0.95);
  transition: opacity 0.4s ease-out, transform 0.4s ease-out;
  transition-delay: 0.3s;
}

.cart-page.page-loaded .empty-cart {
  opacity: 1;
  transform: scale(1);
}

.empty-cart p {
  font-size: 16px;
  color: #666;
  margin-bottom: 20px;
}

.go-shopping-btn {
  display: inline-block;
  padding: 10px 30px;
  background-color: #ff0036;
  color: white;
  font-size: 16px;
  border-radius: 4px;
  transition: all 0.3s ease;
  transform-origin: center;
}

.go-shopping-btn:hover {
  background-color: #e60029;
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(255, 0, 54, 0.3);
}

.go-shopping-btn:active {
  transform: scale(0.98);
}

/* 购物车内容样式 */
.cart-content {
  background-color: #fff;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  width: 100%;
  opacity: 0;
  transform: scale(0.95);
  transition: opacity 0.4s ease-out, transform 0.4s ease-out;
  transition-delay: 0.3s;
}

.cart-page.page-loaded .cart-content {
  opacity: 1;
  transform: scale(1);
}

.cart-items {
  padding: 20px;
}

/* 商品项过渡动画 */
.cart-item-enter-active,
.cart-item-leave-active {
  transition: all 0.3s ease;
}

.cart-item-enter-from {
  opacity: 0;
  transform: translateX(-30px);
}

.cart-item-leave-to {
  opacity: 0;
  transform: translateX(30px);
}

.cart-item-leave-active {
  position: absolute;
  width: calc(100% - 40px);
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 20px 0;
  border-bottom: 1px solid #e5e5e5;
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
}

.cart-item:last-child {
  border-bottom: none;
}

.cart-item:hover {
  background-color: #fafafa;
}

.cart-item.removing {
  animation: removeItem 0.3s ease-out forwards;
}

@keyframes removeItem {
  0% {
    opacity: 1;
    transform: translateX(0);
    height: auto;
  }
  50% {
    opacity: 0.8;
    transform: translateX(50px);
  }
  100% {
    opacity: 0;
    transform: translateX(100px);
    height: 0;
    padding: 0;
    margin: 0;
    border: none;
  }
}

/* 商品图片样式 */
.item-image {
  width: 80px;
  height: 80px;
  margin-right: 20px;
  overflow: hidden;
  background-color: #f5f5f5;
  border-radius: 4px;
  transition: all 0.3s ease;
  position: relative;
}

.item-category-tag {
  position: absolute;
  top: 5px;
  left: 5px;
  background-color: rgba(255, 255, 255, 0.9);
  color: #666;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 10px;
  z-index: 1;
  opacity: 0;
  transform: translateY(-10px);
  transition: all 0.3s ease;
  backdrop-filter: blur(2px);
  display: flex;
  align-items: center;
  gap: 3px;
}

.cart-item:hover .item-category-tag {
  opacity: 1;
  transform: translateY(0);
  background-color: white;
  color: #ff0036;
}

.category-icon {
  font-size: 12px;
}

.cart-item:hover .item-image {
  transform: scale(1.03);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.item-img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  transition: transform 0.5s cubic-bezier(0.34, 1.56, 0.64, 1);
}

.item-image:hover .item-img {
  transform: scale(1.15);
}

/* 商品信息样式 */
.item-info {
  flex: 1;
  transition: transform 0.2s ease;
}

.cart-item:hover .item-info {
  transform: translateX(5px);
}

.item-name {
  font-size: 14px;
  color: #333;
  margin-bottom: 10px;
  transition: color 0.2s ease;
}

.cart-item:hover .item-name {
  color: #ff0036;
}

.item-price {
  font-size: 16px;
  color: #ff0036;
  font-weight: bold;
  transition: transform 0.2s ease;
}

.cart-item:hover .item-price {
  transform: scale(1.05);
}

/* 操作按钮样式 */
.item-actions {
  margin-left: 20px;
  transition: transform 0.2s ease;
}

.cart-item:hover .item-actions {
  transform: translateX(5px);
}

.remove-btn {
  padding: 6px 12px;
  background-color: #f0f0f0;
  color: #666;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.remove-btn:hover {
  background-color: #ff0036;
  color: white;
  transform: scale(1.05);
  box-shadow: 0 2px 8px rgba(255, 0, 54, 0.3);
}

.remove-btn:active {
  transform: scale(0.98);
}

/* 结算区域样式 */
.checkout-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background-color: #f9f9f9;
  border-top: 1px solid #e5e5e5;
  transition: all 0.3s ease;
}

.cart-content:hover .checkout-section {
  background-color: #f5f5f5;
}

.checkout-info {
  display: flex;
  gap: 30px;
  align-items: center;
}

.total-items {
  font-size: 14px;
  color: #666;
}

.total-price {
  font-size: 16px;
  color: #333;
}

.total-price .price {
  font-size: 20px;
  color: #ff0036;
  font-weight: bold;
  display: inline-block;
  transition: transform 0.3s ease;
}

.total-price:hover .price {
  transform: scale(1.1);
}

.animated-number {
  color: #ff0036;
  font-weight: bold;
  font-size: 16px;
}

/* 结算按钮样式 */
.checkout-btn {
  padding: 12px 40px;
  background-color: #ff0036;
  color: white;
  font-size: 16px;
  font-weight: bold;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  transform-origin: center;
}

.checkout-btn:hover {
  background-color: #e60029;
  transform: scale(1.03);
  box-shadow: 0 4px 16px rgba(255, 0, 54, 0.4);
}

.checkout-btn:active {
  transform: scale(0.98);
}

.checkout-btn.checking-out {
  animation: checkoutAnimation 0.5s ease forwards;
}

@keyframes checkoutAnimation {
  0% {
    transform: scale(1);
    background-color: #ff0036;
  }
  50% {
    transform: scale(0.95);
    background-color: #e60029;
  }
  100% {
    transform: scale(1);
    background-color: #4caf50;
  }
}

/* 响应式样式 */
@media (max-width: 768px) {
  .cart-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .item-image {
    margin-right: 0;
    margin-bottom: 10px;
  }
  
  .item-actions {
    margin-left: 0;
    margin-top: 10px;
  }
  
  .checkout-section {
    flex-direction: column;
    gap: 15px;
  }
  
  .checkout-info {
    flex-direction: column;
    gap: 10px;
    align-items: center;
  }
  
  .cart-item-leave-active {
    width: calc(100% - 40px);
  }
}
</style>